package com.roc.web.action.merinfo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.bean.MerinfoChangeSearchVo;
import com.roc.bean.MerinfoDetail;
import com.roc.bean.MerinfoSearchBean;
import com.roc.bean.TermBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.AuditingItem;
import com.roc.pojo.MerinfoChange;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.TblMchtInf;
import com.roc.pojo.TblTermInf;
import com.roc.pojo.TblTermRiskCfg;
import com.roc.pojo.TermInfoTmp;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantChangeServices;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.DateUtil;
import com.roc.util.constant.AuditingResultCodeType;
import com.roc.util.constant.AuditingType;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerinfoStatus;
import com.roc.util.constant.Role;
import com.roc.web.action.agent.MerinfoStatisticsSearchCondition;
@Component
@Scope("prototype")
@Namespace("/merinfoChangeQuery")
public class MerinfoChangeQueryAction extends PaginationBaseAction{

	static Logger logger=Logger.getLogger(MerinfoChangeQueryAction.class);
	private MerinfoChangeQuerySearchCondition searchCondition;
	private MerinfoChange merinfoChange;
	private List<TermBean> termBeanList;

	private MerinfoDetail merinfoDetail;
	
	
	private AuditingItem auditing;//审核意见
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	//private AuditingItem auditing;//审核意见
	
	private TblMchtInf  merinfo; //商户信息表
	
	private TblMchtInf  merinfotmp = new TblMchtInf(); //商户信息表
	
	private InputStream excelFile;
	private String excelName;
	

    @Autowired
    IExcelService excelService;

	@Autowired
	IPagenitionService pagenitionService;
	
	@Autowired
	IPageService pageService; //走备库
	
	@Autowired
	IPowerInfoService iPowerInfoService;
	
	@Autowired
	IMerchantServices merinfoService;
	
	@Autowired
        IMerchantChangeServices merinfoChangeService;
	
	@Autowired
	IorgService orgService;
	@Autowired
	ITerminalService terminalService; 
	
	
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/merinfo/merinfoChangeQuery.jsp")
    })
	public String init() throws Exception{
		Operators loginOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		try {
			//初始化机构
                        orgList = orgService.queryOrgList();
			getRequest().setAttribute("product", ConfigMerinfoUtil.getProductList());//开通产品信息
                        getRequest().setAttribute("posFunction", ConfigMerinfoUtil.getPosFunction(ConfigMerinfoUtil.ALL_FUNCTION, false));//开通产品信息
                        getRequest().setAttribute("posType", ConfigProperties.getSysDB1("Terminal_Type",true));//终端类型
                        
		}catch (Exception e) {
			// TODO: handle exception
			addActionError("加载信息失败，请联系客服人员");
			logger.error(e.getMessage(),e);
		}
			
	   return SUCCESS;
    }
	
	@Action(value = "queryMerinfo", 
			results = { @Result(name = "success", location = "/pages/merinfo/merinfoChangeQuery.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String queryMerinfo() throws Exception{
	    Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		
		if(searchCondition==null){
			searchCondition=(MerinfoChangeQuerySearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new MerinfoChangeQuerySearchCondition();
			}
		}
		
		try {
			init();
			//运营角色转换
			Map<String, String> map=iPowerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
            String orgCode=map.get("orgCode");
            String superRole= map.get("superRole");
            String opRealId =map.get("opRealId");
            searchCondition.setGroupCd(map.get("groupCd"));
            searchCondition.setOrgCode(orgCode);//当前查询人员所属收单机构
            searchCondition.setOneOrgCode(op.getOneagentid());//机构
            searchCondition.setRoleId(superRole);// 角色
            searchCondition.setOpId(opRealId);//当前人员id

            if(Role.MERCHANT.getCode().equals(op.getRoleType())){//商户
                searchCondition.setMerchantNo(String.valueOf(op.getAccountNo()));
            }
			int rows=pageService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pageService.findAllSQL(searchCondition, calcuStart(getCurrentPage()),  Constance.PAGE_MAX_SIZE);
			}
			List<MerinfoChangeSearchVo> msList=new ArrayList<MerinfoChangeSearchVo>();
                        if(searchRsList.size()>0 && searchRsList!=null){
                                
                                Iterator iterator=searchRsList.iterator();
                                while (iterator.hasNext()) {
                                        Object[] obj= (Object[])iterator.next();
                                        MerinfoChangeSearchVo  msb=new MerinfoChangeSearchVo(); 
                                        msb.setId(Constance.Null2EmptyTrim(obj[0]));
                                        msb.setDealCode(Constance.Null2EmptyTrim(obj[1]));//变更类型
                                        msb.setMid(Constance.Null2EmptyTrim(obj[2]));//商户号
                                        msb.setDtCreateTime(Constance.Null2EmptyTrim(obj[3]));//更改申请时间
                                        msb.setDtAuditorTime(Constance.Null2EmptyTrim(obj[4]));//审核时间
                                        msb.setStatus(Constance.Null2EmptyTrim(obj[5]));//状态
                                        msb.setName(Constance.Null2EmptyTrim(obj[6]));//工商注册名
                                        msb.setNameBusi(Constance.Null2EmptyTrim(obj[7]));//商户简称
                                        msb.setContactName(Constance.Null2EmptyTrim(obj[8]));//业务联系人
                                        
                                        String phone = Constance.Null2EmptyTrim(obj[9]);//手机号码
                                        if(null != op.getAgentType() && !op.getAgentType().equals("1")){
                                            msb.setContactPhoneNo(phone.substring(0, 3)+"****"+phone.substring(phone.length()-4));//手机号 
                                        }else{
                                            msb.setContactPhoneNo(phone);//手机号
                                        }
                                        
                                        msb.setCertif(Constance.Null2EmptyTrim(obj[10]));//法人代表
                                       
                                        String cardNo = Constance.Null2EmptyTrim(obj[11]); //法人代表证件号码
                                        if(null != op.getAgentType() && !op.getAgentType().equals("1")){
                                            msb.setCertifNo(cardNo.substring(0,3)+"****"+cardNo.substring(cardNo.length()-4));//证件号  
                                        }else{
                                            msb.setCertifNo(cardNo);//证件号
                                        }
                                        msb.setRegAddr(Constance.Null2EmptyTrim(obj[12]));
                                        msb.setMerKind(Constance.Null2EmptyTrim(obj[13]));
                                        msb.setAgentId(Constance.Null2EmptyTrim(obj[14]));
                                        msb.setRemark(Constance.Null2EmptyTrim(obj[15]));
                                        msb.setOperators(Constance.Null2EmptyTrim(obj[16]));
                                        msList.add(msb);
                                }
                        }
			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, msList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (ServiceException e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	
	// 导出excel
        @Action(value = "excelMerinfoChangeC2List", results = {
                        @Result(name = "success", type = "stream", params = {
                                        "contentType", "application/vnd.ms-excel", "inputName",
                                        "excelFile", "contentDisposition",
                                        "attachment;filename=${excelName}.xls", "bufferSize",
                                        "1024*3" }),
                        @Result(name = "error", location = "/error.jsp"),
                        @Result(name = "input", location = "/pages/merinfo/merinfoChangeQuery.jsp")})
        public String settingExcelqQuery() throws Exception {
                try {
                        
//                        Operators op = (Operators) ActionContext.getContext()
//                        .getSession().get(Constant.SESSION_LOGIN_MERCHANT);
//                        
                        
                        if(searchCondition==null){
                            searchCondition=(MerinfoChangeQuerySearchCondition)getSearchConditionFromSession();
                            if(searchCondition==null){
                                    searchCondition=new MerinfoChangeQuerySearchCondition();
                            }
                        }
//                        if(!op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || !op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS)){
//                            addActionError("此登陆账号没有权限");
//                            return ERROR;
//                        }
                        
                        List<MerinfoChange> c2List = merinfoChangeService.queryC2List(searchCondition.getMinDate(), searchCondition.getMaxDate());
                        
                        if(c2List.size()>0){
                            setExcelName(new String("变更审核通过后结算信息导出".getBytes(), "ISO8859-1"));

                            HSSFWorkbook work = excelService.exportMerinfoChangeC2Info(c2List,searchCondition.getMinDate(),searchCondition.getMaxDate());
                            ByteArrayOutputStream output = new ByteArrayOutputStream();  
                            work.write(output);  
                               
                            byte[] ba = output.toByteArray();  
                            excelFile = new ByteArrayInputStream(ba);  
                            output.flush();  
                            output.close();
                        }else{
                            addActionMessage("导出变更结算信息："+c2List.size());
                            getRequest().setAttribute(SEARCH_RS_LIST, c2List);
                            return INPUT;
                        }
                         
                } catch (Exception e) {
                        logger.info("######商户信息导出Excel明细失败######");
                        addActionError(e.getMessage());
                        return ERROR;
                } 
                return SUCCESS;
        }
	
	/*@Action(value = "editMerinfo", 
			results = { @Result(name = "success", location = "/pages/merinfo/merinfoEdit.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String editMerinfo() throws Exception{
		try {
			if(merinfoChange.getMid()==null || merinfoChange.getMid().equals("")){
				addActionError("审核商户查询失败~！");
				return ERROR;
			}
			merinfoChange=merinfoService.queryUniqueById(merinfoChange.getId());
		//	merinfoChange.setUrl1("");
			merinfoDetail=merinfoService.queryMerByMid(merinfoChange.getMid());
			List<Object> audtingList=new ArrayList<Object>();
			audtingList=merinfoService.queryAuditingListChange(merinfoChange.getMid(),null);
		    getRequest().setAttribute("audtingList", audtingList);
		    getRequest().setAttribute("bankList", ConfigProperties.getBankListProperties());
		    if(merinfoChange.getDealCode().equals("C5")){
		    	termBeanList=terminalService.queryTermChangeByMid(merinfoChange.getMid());
		    }
		    if(merinfoChange.getDealCode().equals("C8")){
		    	 List< TermBean> terList=terminalService.queryByMid(merinfoChange.getMid());//终端信息	
				
				 getRequest().setAttribute("terList", terList);
		    }
		
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
			
		return SUCCESS;
	}*/
	/*@Action(value = "saveEdit", 
			results = { @Result(name = "success", location = "/pages/merinfo/merinfoChangeQuery.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String saveEdit() throws Exception{
	    Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		MerinfoChange merinfoTemp=null;
		try{
			merinfoTemp=merinfoService.queryUniqueById(merinfoChange.getId());
			merinfoTemp=dealSave(merinfoTemp,merinfoChange);
			if(merinfoChange.getDealCode().equals("C5")){
				merinfoService.insertMerinfoChangeTerm(termBeanList, merinfoTemp.getMid(),op);
			}
			if(merinfoChange.getDealCode().equals("C8")){ 
				List<String> tList=this.getMulti_sel_str();
				terminalService.deleteTermInfoTmpByMid(op.getAccountNo(), merinfoTemp.getMid());
				for(int i=0;i<tList.size();i++){
					terminalService.insertTermInfoTmpByTid(tList.get(i), op.getAccountNo(), merinfoTemp.getMid());
				}
			}
			merinfoService.updateMerinfoChange(merinfoTemp);
			
			
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
		
		return queryMerinfo();
	}*/
	
	@Action(value = "queryById", 
			results = { @Result(name = "success", location = "/pages/merinfo/merinfoChangeDetail.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String queryById() throws Exception{
	        Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
		    init();
			if(merinfoChange.getId()==null || merinfoChange.getId().equals("")){
				addActionError("查询商户变更详情失败~！");
				return ERROR;
			}
			
			//商户变更信息
                        merinfoChange=merinfoChangeService.queryMerinfoChangeById(merinfoChange.getId());
                        
                        merinfoChange.setDealCode(merinfoChange.getDealCode().trim().toString());
			//商户信息
			merinfo = merinfoChangeService.queryMerinfoDetailInfo(merinfoChange.getMid(),true,op.getAgentType());
			
			
			String terIds = merinfoChange.getTerId();
			if(null != terIds){
			    
			    String[] terId = terIds.split(",");
			    List<TblTermInf> terminfoList = merinfo.getTerminfoList();
			    ArrayList<TblTermInf> terminfoListTmp = new ArrayList<TblTermInf>();
			    
			    for (String id : terId) {
                                for (TblTermInf tblTermInf : terminfoList) {
                                    if(tblTermInf.getId().getTermId().equals(id)){
                                        terminfoListTmp.add(tblTermInf);
                                    }
                                }
                                merinfotmp.setTerminfoList(terminfoListTmp);
                            }
			}
			
			
			/*//审核详情
			List<Object> audtingList=new ArrayList<Object>();
			audtingList=merinfoChangeService.queryAuditingListChange(merinfoChange.getMid(),null);
		        getRequest().setAttribute("audtingList", audtingList);
		        
		        List< TermBean> terList=terminalService.queryByMid(merinfoChange.getMid());//终端信息
			getRequest().setAttribute("terList", terList);
			getRequest().setAttribute("terTmpList", terminalService.queryTermNULLTmpByMid(merinfoChange.getMid()));*/
		
    	}catch (Exception e) {
			logger.error(e.getMessage(),e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
			
		return SUCCESS;
	}
	
	private MerinfoChange dealSave(MerinfoChange merinfoTemp,MerinfoChange merinfoChange){
		/*if(!merinfoChange.getDealCode().equals("C7")){
			merinfoChange.setMerBrName(merinfoDetail.getMerBrName());
			merinfoChange.setTel(merinfoDetail.getTel());
			merinfoChange.setPerPhone(merinfoDetail.getPerPhone());
		}*/
		if(merinfoChange.getDealCode().equals("C1")){
			merinfoTemp.setAddr(merinfoChange.getAddr());
			merinfoTemp.setEngBrName(merinfoChange.getEngBrName());
			merinfoTemp.setEngName(merinfoChange.getEngName());
		}else if(merinfoChange.getDealCode().equals("C2")){
			if(!Constance.Null2EmptyTrim(merinfoChange.getSettBankId()).equals("")){
				merinfoTemp.setSettBankId(merinfoChange.getSettBankId());
			}
			merinfoTemp.setAccBank(merinfoChange.getAccBank());
			merinfoTemp.setAccNo(merinfoChange.getAccNo());
			merinfoTemp.setContact(merinfoChange.getContact());
		}else if(merinfoChange.getDealCode().equals("C3")){
			merinfoTemp.setCommAmt(merinfoChange.getCommAmt());
			merinfoTemp.setCommMode(merinfoChange.getCommMode());
			merinfoTemp.setCommRate(merinfoChange.getCommRate());
			
		}else if(merinfoChange.getDealCode().equals("C4")){
			merinfoTemp.setAmount1(merinfoChange.getAmount1());
			merinfoTemp.setAmount2(merinfoChange.getAmount2());
			merinfoTemp.setDayAmount1(merinfoChange.getDayAmount1());
			merinfoTemp.setDayAmount2(merinfoChange.getDayAmount2());
			merinfoTemp.setMouthAmount1(merinfoChange.getMouthAmount1());
			merinfoTemp.setMouthAmount2(merinfoChange.getMouthAmount2());
		} 
		
		merinfoTemp.setUrl1(merinfoChange.getUrl1());
		merinfoTemp.setUrl2(merinfoChange.getUrl2());
		if(merinfoChange.getUrl3()!=null){
			merinfoTemp.setUrl3(merinfoChange.getUrl3());
		}
		merinfoTemp.setStatus("W");
		return merinfoTemp;
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_BEAN_MERINFO_CHANGE_QUREY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_BEAN_MERINFO_CHANGE_QUREY);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	public MerinfoChangeQuerySearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(MerinfoChangeQuerySearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public MerinfoChange getMerinfoChange() {
		return merinfoChange;
	}

	public void setMerinfoChange(MerinfoChange merinfoChange) {
		this.merinfoChange = merinfoChange;
	}

	public MerinfoDetail getMerinfoDetail() {
		return merinfoDetail;
	}

	public void setMerinfoDetail(MerinfoDetail merinfoDetail) {
		this.merinfoDetail = merinfoDetail;
	}

	public AuditingItem getAuditing() {
		return auditing;
	}

	public void setAuditing(AuditingItem auditing) {
		this.auditing = auditing;
	}

    public List<TblInsInf> getOrgList() {
        return orgList;
    }

    public void setOrgList(List<TblInsInf> orgList) {
        this.orgList = orgList;
    }

    public TblMchtInf getMerinfo() {
        return merinfo;
    }

    public void setMerinfo(TblMchtInf merinfo) {
        this.merinfo = merinfo;
    }

    public TblMchtInf getMerinfotmp() {
        return merinfotmp;
    }

    public void setMerinfotmp(TblMchtInf merinfotmp) {
        this.merinfotmp = merinfotmp;
    }

    public String getExcelName() {
        return excelName;
    }

    public void setExcelName(String excelName) {
        this.excelName = excelName;
    }

    public InputStream getExcelFile() {
        return excelFile;
    }

    public void setExcelFile(InputStream excelFile) {
        this.excelFile = excelFile;
    }



	
}
